package cc.facesign.admin.controller;


import cc.facesign.admin.bean.TblUser;
import cc.facesign.admin.bean.query.UserQuery;
import cc.facesign.admin.bean.vo.AddUserVo;
import cc.facesign.admin.bean.vo.UserVo;
import cc.facesign.admin.client.OssClient;
import cc.facesign.admin.service.TblConfUserService;
import cc.facesign.admin.service.TblManageDeptService;
import cc.facesign.admin.service.TblUserService;
import cc.facesign.admin.utils.PageUtils;
import cc.facesign.admin.utils.PowerUtils;
import cc.facesign.common.exception.FacesignException;
import cc.facesign.common.utils.bean.R;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-05-06
 */
@RestController
@RequestMapping("/admin/user")
@Api(description = "用户管理")
public class TblUserController {

    @Autowired
    private TblUserService userService;

    @Autowired
    private PowerUtils powerUtils;

    @Autowired
    private TblManageDeptService manageDeptService;

    @Autowired
    private TblConfUserService confUserService;

    @Autowired
    private OssClient ossClient;

    /**
     * deptIds是一个list集合
     * 当 rootDeptId 为0时，查找范围为所有部门
     * @param current 页数
     * @param limit 每页数量
     * @param query vo
     * @return
     */
  //  @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("查用户信息【分页+条件】")
    @PostMapping("/getConditionPage/{current}/{limit}")
    public R getConditionPage(@PathVariable("current") Integer current,
                              @PathVariable("limit") Integer limit,
                              @RequestBody(required = false) UserQuery query) {
        String currDeptId = powerUtils.getCurrentUser().getDeptId();

        List<String> deptIds = query.getDeptIds();
        String rootDeptId = query.getRootDeptId();

        // 权限校验
        HashSet<String> set = powerUtils.getCurrentChildDeptIdSet();
        if (!StringUtils.isEmpty(rootDeptId) && !set.contains(rootDeptId)) {
            throw new FacesignException(R.ERROR, "权限非法");
        }

        if (deptIds != null) {
            for (String deptId : deptIds) {
                if (!set.contains(deptId) && !currDeptId.equals(deptId))
                    throw new FacesignException(R.ERROR, "权限非法");
            }
        }

        if (deptIds == null || deptIds.size() == 0) {
            deptIds = new ArrayList<>(powerUtils.getCurrentChildDeptIdSet());
            query.setDeptIds(deptIds);
        }

        List<UserVo> list = userService.getInfoListByQuery(query);
        IPage<UserVo> page = PageUtils.page(list, current, limit);
        return R.ok().data("page", page);
    }

    @ApiOperation("获取当前登录用户的信息")
    @GetMapping("/getCurrentUserInfo")
    public R getCurrentUserInfo() {
        TblUser user = powerUtils.getCurrentUser();
        UserVo info = userService.getInfoById(user.getId());
        return R.ok().data("data", info);
    }

    @PreAuthorize("@ex.hasAuthorith('root:exe')")
    @ApiOperation("更新头像")
    @PostMapping("/uploadPic/{userId}")
    public R uploadPic(@PathVariable String userId, MultipartFile file) {
        String url = (String) ossClient.upload(file).getData().get("url");
        TblUser user = userService.getById(userId);
        user.setAvatar(url);
        userService.updateById(user);

        return R.ok().data("url", url);
    }

    /**
     * 1. 只有上级能删
     * 2. 管理员不能删
     * 3. 会议创建者不能删
     * 4. 如果用户参加了会议，同时会删除会议关联
     * @param userId 用户id
     * @return
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe')")
    @ApiOperation("删除用户")
    @DeleteMapping("/deleteUser/{userId}")
    public R deleteUser(@PathVariable String userId) {
        if (!powerUtils.isMaster(userId)) {
            return R.error().message("没有管理该用户的权限");
        }

        // 是否是部门管理者
        if (userService.countManageForDept(userId) != 0) {
            return R.error().message("用户管理着部门或会议，不能直接删除");
        }

        // 是否是会议创建者
        if (userService.countManageForConf(userId) != 0) {
            return R.error().message("用户管理着会议，不能直接删除");
        }

        // 用户参加会议，就解除会议关联
        List<String> confIds = userService.getJoinConfIds(userId);
        if (confIds.size() != 0) {
            for (String confId : confIds) {
                confUserService.deleteBatch(confId, Collections.singletonList(userId));
            }
        }


        userService.removeById(userId);

        return R.ok();

    }

    @ApiOperation("按id批量查用户信息")
    @PostMapping("/getInfoBatch")
    public R getInfoBatch(@RequestBody List<String> ids) {
        List<UserVo> res = userService.getInfoByIdBatch(ids);
        return R.ok().data("data", res);
    }

    /**
     * cardId不能重复，如果重复，都不会添加，并且返回有问题的信息.
     * birthday 参数随便追加一个 00:00。不然接收会有问题
     * @param deptId
     * @param data
     * @return
     */
    @ApiOperation("向部门中创建用户")
    @PostMapping("/createUser/{deptId}")
    public R addUser(@PathVariable String deptId, @RequestBody List<AddUserVo> data) {
        if (!powerUtils.getCurrentChildDeptIdSet().contains(deptId)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        List<AddUserVo> errs = userService.createUserBatch(deptId, data);

        if (errs.size() == 0) return R.ok();
        else return R.error().data("errs", errs);
    }
}

